package com.example.ymm.modules1.service.dto.common;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelDataListener extends AnalysisEventListener<ExcelData> {
    private List<ExcelData> dataList = new ArrayList<>();
    // 用于存储读取到的图片数据
    Map<Integer, byte[]> imageMap = new HashMap<>();
    @Override
    public void invoke(ExcelData data, AnalysisContext context) {
        // 获取数据所在行的行号，后续和文件中的图片数据做匹配使用
        Integer rowIndex = context.readRowHolder().getRowIndex();
        data.setRowId(rowIndex);
        dataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    // 重写图片处理方法
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        super.invokeHeadMap(headMap, context);
    }

    public void extra(String sheetName, Integer rowIndex, Integer columnIndex, String extraType, Object content, AnalysisContext context) {
        // 处理图片
        if ("image".equals(extraType)) {
            // content是图片的字节数组
            imageMap.put(columnIndex, (byte[]) content);
            saveImage((byte[]) content, "image_" + rowIndex + "_" + columnIndex + ".jpg");
        }
    }
    // 保存图片到本地
    private void saveImage(byte[] imageBytes, String fileName) {
        try (FileOutputStream fos = new FileOutputStream("E:\\照片\\test\\" + fileName)) {
            fos.write(imageBytes);
            fos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<ExcelData> getDataList() {
        return dataList;
    }
}

